package com.ddl.aop;


import com.ddl.common.enums.ErrorCode;
import com.ddl.common.enums.Platform;
import com.ddl.common.exception.BusinessException;
import com.ddl.common.exception.ExceptionUtil;
import com.ddl.common.exception.ResultModel;
import com.ddl.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class TokenAspect {

    private static Logger logger = LogManager.getLogger(TokenAspect.class);
    @Resource
    private UserService userService;

    @Pointcut("execution(* com.ddl.controller.core..*(..))")
    public void tokenAop() throws Exception {
        logger.info("验证token进入切点");
    }

    @Around("tokenAop()")
    public Object doBefore(ProceedingJoinPoint pJoinPoint) throws Throwable {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        // 接收到请求，记录请求内容
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 记录下请求内容
            logger.info("URL : " + request.getRequestURL().toString());
            logger.info("HTTP_METHOD : " + request.getMethod());
            logger.info("IP : " + request.getRemoteAddr());
            logger.info("CLASS_METHOD : " + pJoinPoint.getSignature().getDeclaringTypeName() + "." + pJoinPoint.getSignature().getName());
            String userId = request.getHeader("userId");
            String token = request.getHeader("token");

            logger.info("Token验证----userId=" + userId);
            logger.info("Token验证----token=" + token);


            if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(token)) {
                logger.error("用户{}登录过期，请重新登录", userId);
                throw new BusinessException(ErrorCode.LOGIN_ERROR_401);
            }

            userService.verifyUser(userId, token, Platform.APP);
        }catch (Exception e){
            logger.error("Token验证异常",e);
            resultModel= ExceptionUtil.getMessageException(e);
            return resultModel;
        }
        return pJoinPoint.proceed();
    }

}
